// pages/bureauList/bureauList.js
import {
  picUrl,
  launchAppCopy
} from '../../utils/util.js';
import {
  activityList,
  userConventionOrder,
  getTicketInfos,
  placeOrder,
  userOrder,
  miniProgPay
} from '../../utils/getData.js'
const getopen = require('../../utils/maxutil.js');
const config = require('../../utils/config.js');
import {
  formatTime
} from '../../utils/util.js';
import {
  conventionDetail
} from '../../utils/getData.js'


const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    minModel: app.globalData.minModel, //小机型iphone8
    list: [],
    pageNum: 1, //当前页数
    nolist: false, //列表数据没有更多
    conventionId: "",
    cardData: {}, //卡片上的数据
    // juInvalidation:1, //局是否失效 1失效，2未失效
    isCardShow: false, //卡片是否显示
    isBlurryShow: false, //列表上层的模糊层
    headerStatus: 1, //1:箭头分离头像,2箭头头像,3头像关闭图标  导航状态
    headerTop: getApp().globalData.headerTop,

    convention: '', //活动数据
    headerdata: {}, //传给头部headers组件的数据
    // topheight:0, //头部高度，计算底部列表区域用

    isBuyTickets: false, //是否购票
    buyTicketsPopover: false, //购票弹框
    buyTicketsAnimation: false, //购票弹框动画，主要是关闭时先给个动画再销毁
    ticketsNumber: 1, //票数量
    ticketsInfoList: [], //票种列表

    payPopover: false, //支付层
    orderInformation: '', //订单信息
    orderId: '', //生成的订单ID,支付接口用
    conventiondata: '',
    isbookedListShow: false, //已购票列表是否显示
    orderList: [], //已购票列表
    swiperTab: 0, //轮播图显示第几个
    payOver: false, //支付完成的状态
    wenquan: false,
    goAppPopover: false, //进入有局app弹框状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // if(wx.getStorageSync('openId')){
    let conventionId = '';
    console.log("页面参数：",options)
    //扫码进来
    if (options.scene && options.scene) {
      conventionId = options.scene
    }
    //页面内跳入
    if (options.conventionId && options.conventionId) {
      conventionId = options.conventionId;
    }
    if (wx.getStorageSync('userId')) {
      this.getdetail(conventionId);
    } else {
      this.login(conventionId);
    }
    //登录
    // }else{
    //   //未注册的用户
    //   // wx.navigateTo({
    //   //   url: '../login/login'
    //   // })
    //   console.log("user not login")
    // }

  },

  login(conventionId) {
    let than = this;
    getopen.loginOpenid().then(res => {
      console.log('取到了openid')
      this.getdetail(conventionId);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // let than = this;
    // let query = wx.createSelectorQuery();
    // query.select('.topbox').boundingClientRect(rect=>{
    //   let height = rect.height;
    //   than.setData({
    //     topheight:height
    //   })
    //   console.log(height);
    //   }).exec();
  },
  // 局列表点击事件
  goinfo(event) {
    let activityId = event.currentTarget.dataset.activityid;
    console.log(activityId)

    this.getActivityDetail(activityId);
  },

  //卡片取消事件
  cardClose() {
    this.setData({
      headerStatus: 1,
      isCardShow: false,
      isBlurryShow: false,
      cardData: [],
    })
  },
  //导航关闭回调
  headerClose() {
    console.log('关闭啦')
    this.setData({
      headerStatus: 1,
      isBlurryShow: false,
      isbookedListShow: false,
      payPopover: false,
      isCardShow: false,
    })
  },

  // 分享事件回调
  _cardShare() {
    console.log('分享啦')
  },

  //查询局列表
  getActivityList() {
    let than = this;
    const {
      list
    } = this.data;
    let data = {
      userId: wx.getStorageSync('userId'),
      pageNum: than.data.pageNum,
      pageSize: 10,
      conventionId: app.globalData.conventionInfo.headerdata.conventionId,
      searchFlag: 0
    }
    activityList(data).then(res => {
      if (res.success) {
        if (res.result.records.length == 0) {
          than.setData({
            nolist: true
          })
        } else {
          let newrecords = res.result.records.map((item) => {
            return {
              ...item,
              activityCoverPage: picUrl('activity/img/', item.activityCoverPage),
              activityBlurCoverPage: picUrl('activity/img/', item.activityBlurCoverPage),
              activityDate: item.activityDate.slice(5).replace("-", "/"),
              activityUserMap: item.activityUserMap.participantlist.map((b) => {
                return {
                  ...b,
                  avatarPath: picUrl('', b.avatarPath),
                  userPic: picUrl('', b.userPic)
                }
              }),
              sponsorUser: {
                ...item.sponsorUser,
                avatarPath: picUrl('', item.sponsorUser.avatarPath)
              }
            }
          })
          console.log(newrecords)
          than.setData({
            list: list.concat(newrecords)
          })

        }

      }

    })
  },
  //局详情
  getActivityDetail(activityId) {
    let than = this;
    //因多个页面会有局详情接口，使用公共方法转换数据，只需要传activityId
    getopen.getActivityDetail(activityId).then(res => {
      //判断活动是否结束
      // let currentTime = formatTime(new Date()); //当前时间
      //  currentTime = currentTime.substring(0,currentTime.length-3);
      //  let activityEndTime = res.activityDate.replace(/-/g,"/") +' '+ res.activityEndTime  //局结束时间
      let data = {
        ...res,
        //  activityDate:res.activityDate.slice(5).replace(/-/g,"/")
      }
      than.setData({
        cardData: data, //卡片上的数据
        // juInvalidation: currentTime >= activityEndTime ? 1 : 2, //局是否失效
      }, () => {
        //卡片显示
        than.setData({
          headerStatus: 2,
          isCardShow: true,
          isBlurryShow: true,
        })
      })
    })
  },
  //大型活动详情 
  getConventionDetail() {
    //global全局传参，避免重复打接口
    let than = this;
    than.setData({
      convention: app.globalData.conventionInfo,
      headerdata: app.globalData.conventionInfo.headerdata,
    })
  },
  //用户-活动是否购票
  getuserConventionOrder() {
    let than = this;
    let data = {
      conventionId: app.globalData.conventionInfo.headerdata.conventionId,
      userId: wx.getStorageSync('userId'),
    }
    userConventionOrder(data).then(res => {
      let newlist = []
      res.result.map(a => {
        a.orderQRCodes.map((b, index) => {
          let c = {
            ...b,
            ticketNums: a.ticketNums,
            currentNums: index + 1
          }
          newlist.push(c)
        })
      })

      console.log(newlist)
      than.setData({
        isBuyTickets: res.result.length >= 1,
        // isBuyTickets:true,
        orderList: newlist
      })

    })
  },
  //轮播图，左箭头
  swipeLeft() {
    const {
      swiperTab
    } = this.data;
    if (swiperTab == 0) return false
    this.setData({
      swiperTab: swiperTab - 1
    })
  },
  //轮播图，右箭头
  swiperRight() {
    const {
      swiperTab,
      orderList
    } = this.data;
    if (swiperTab == orderList.length - 1) return false;
    this.setData({
      swiperTab: swiperTab + 1
    })
  },
  //轮播图，主体部份滑动事件
  swiperChange: function (e) {
    var that = this;
    that.setData({
      swiperTab: e.detail.current
    });
  },

  //滚动到底部 加载更多数据
  lower(e) {
    const {
      pageNum,
      nolist
    } = this.data
    if (nolist) return false;
    this.setData({
      pageNum: pageNum + 1
    }, () => {
      this.getActivityList()
    })
  },
  //获取大型活动票种
  getTicketInfos() {
    let data = {
      conventionId: app.globalData.conventionInfo.headerdata.conventionId
    }
    getTicketInfos(data).then(res => {
      //增加字段区分选中与未选中的状态
      let newlist = res.result.map((v, index) => {
        if (index == 0) {
          return {
            ...v,
            isSelected: true
          }
        } else {
          return {
            ...v,
            isSelected: false
          }
        }
      })
      console.log(newlist)
      this.setData({
        ticketsInfoList: newlist
      })
    })
  },

  //订票
  booking() {
    wx.vibrateShort();

    this.setData({
      buyTicketsPopover: true,
      buyTicketsAnimation: true
    })
    this.getTicketInfos();
  },
  //已购票事件
  booked() {
    wx.vibrateShort();

    this.getuserConventionOrder();
    this.setData({
      isBlurryShow: true,
      isbookedListShow: true,
      headerStatus: 2,
      payOver: false,
      wenquan: true,
    })
  },
  //再次购票事件
  againBooking() {
    wx.vibrateShort();

    let than = this;
    this.setData({
      headerStatus: 1,
      isBlurryShow: false,
      isbookedListShow: false
    }, () => {
      than.booking()
    })
  },
  //关闭购票弹框
  ticketsClose() {
    let than = this;
    console.log('关闭购票')
    this.setData({
      buyTicketsAnimation: false,
    })
    //动画走完了再销毁弹框
    setTimeout(() => {
      than.setData({
        buyTicketsPopover: false
      })
    }, 300);
  },
  //选中票事件
  onPick(event) {
    const {
      ticketsInfoList
    } = this.data;
    let ticketid = event.currentTarget.dataset.ticketid;

    wx.vibrateShort();
    ticketsInfoList.map((item, index) => {
      if (ticketid == item.ticketId) {
        if (!item.isSelected) {
          ticketsInfoList[index].isSelected = true;
        }
      } else {
        ticketsInfoList[index].isSelected = false;
      }
    })

    this.setData({
      ticketsInfoList
    })
  },
  //加票
  ticketsAdd() {
    const {
      ticketsNumber
    } = this.data
    this.setData({
      ticketsNumber: ticketsNumber + 1
    })
  },
  //减票
  ticketsLess() {
    const {
      ticketsNumber
    } = this.data
    if (ticketsNumber == 1) return false;
    this.setData({
      ticketsNumber: ticketsNumber - 1
    })
  },

  goWebview() {
    wx.vibrateShort();
    console.log("aaa:", this.data.convention),
      wx.navigateToMiniProgram({
        appId: 'wxebadf544ddae62cb',
        path: 'pages/survey/index?sid=7558128&hash=3709',
        extraData: {
          foo: 'bar'
        },
        success(res) {
          console.log("wenquan:", this.data.wenquan)


        }
      }),
      this.setData({
        wenquan: false
      })

  },

  cancelWebview() {

    this.setData({
      wenquan: false
    })

  },
  //用户购票 冲事件
  placeOrder() {
    wx.vibrateShort();
    wx.setStorageSync('avatarstatus', app.globalData.conventionInfo.avatarstatus)
    if (wx.getStorageSync('status') == 0) {
      wx.navigateTo({
        url: '../login/login'
      })

    }
    const {
      ticketsNumber,
      ticketsInfoList
    } = this.data;
    let than = this;
    let conventionId = '';
    let ticketId = '';
    let ticketAmount = '';
    let orderInformation = {}
    ticketsInfoList.map(item => {
      if (item.isSelected) {
        conventionId = item.conventionId;
        ticketId = item.ticketId;
        ticketAmount = item.ticketAmount;
        //支付层需要的展示数据
        orderInformation = {
          ticketName: item.ticketName,
          ticketAmount: item.ticketAmount,
          totalFee: ticketAmount * ticketsNumber,
        }
        than.setData({
          orderInformation,
          headerStatus: 2,
        })
      }
    })
    let data = {
      conventionId,
      ticketId,
      ticketNums: ticketsNumber,
      totalFee: ticketAmount * ticketsNumber,
      userId: wx.getStorageSync('userId')
    }
    placeOrder(data).then(res => {
      if (res.success) {
        this.setData({
          buyTicketsPopover: false,
          buyTicketsAnimation: false,


          orderId: res.result.orderId
        })
        if (wx.getStorageSync('status') == 1 || wx.getStorageSync('status') == 9 || wx.getStorageSync('status') == 100) {
          this.setData({
            payPopover: true,
            isBlurryShow: true
          })
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 1000
        })
      }
    })
  },
  //微信支付事件
  goPay() {
    wx.vibrateShort();

    const {
      orderId,
      orderInformation
    } = this.data;
    let than = this;
    let params = {
      body: orderInformation.ticketName,
      openId: wx.getStorageSync('openId'), //
      orderId,
      totalFee: orderInformation.totalFee,
      type: 0
    }
    let header = {
      'content-type': 'application/json', //json格式
    }

    // miniProgPay(data).then(res => {
    //   console.log(res)
    //   
    // })
    wx.request({
      url: config.host + 'wxpay/miniProgPay', //https://www.bonaxl.com:8094/api/aboard/wxpay/miniProgPay
      method: "POST",
      data: params,
      header: header,
      success: function (res) {
        console.log(res)
        let newdata = res.data.result

        wx.requestPayment({
          timeStamp: newdata.timeStamp,
          nonceStr: newdata.nonceStr,
          package: newdata.package,
          signType: newdata.signType,
          paySign: newdata.paySign,
          success(res) {
            console.log('支付成功' + res)
            than.userOrder();
          },
          fail(res) {
            console.log('支付失败' + res)
          }
        })

      },
      fail: function (error) {}
    })

    // than.userOrder();

  },
  //用户-支付回调页面
  userOrder() {
    let than = this;
    const {
      orderId
    } = this.data;
    let data = {
      orderId
    }
    let header = {
      // 'content-type': 'application/json',  //json格式
      'content-type': 'application/x-www-form-urlencoded',  //form格式
    }
    wx.request({
      url: "https://www.bonaxl.com:8094/api/aboard/v1/pub/convention/userOrder",
      method: "POST",
      data: data,
      header: header,
      success: function (res) {
        if (res.data.success) {
          console.log(res)
        let newlist = []
        res.data.result.map(a => {
          a.orderQRCodes.map((b, index) => {
            let c = {
              ...b,
              ticketNums: a.ticketNums,
              currentNums: index + 1
            }
            newlist.push(c)
          })
        })
          than.setData({
            payOver: true,
            isBuyTickets: true,
            isbookedListShow: true,
            payPopover: false,
            swiperTab: 0,
            orderList: newlist,
            wenquan: false
          })
        }
      },
      fail: function (error) {
        reject(error)
      },
      complete: function (aaa) {
        console.log(aaa)
      }
    })

  },

  //  打开有局app弹框
  openApp() {
    wx.vibrateShort();

    console.log('打开有局app')
    //是否安卓机
    if (!app.globalData.isiPhone) {
      wx.navigateTo({
        url: '../androidMessage/androidMessage'
      })
      return false
    }

    this.setData({
      goAppPopover: true
    })
  },
  //有局app弹框上的按钮事件
  launchAppError(e) {
    console.log(7777)

    //复制文字到剪贴板
    launchAppCopy()
  },
  //透明背景事件
  ontransparentBj() {
    this.setData({
      goAppPopover: false
    })
    this.ticketsClose();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log("分享参数:",'pages/bureauList/bureauList?conventionId=' + this.data.convention.headerdata.conventionId)
    return {
      path: 'pages/bureauList/bureauList?conventionId=' + this.data.convention.headerdata.conventionId,
      imageUrl: this.data.conventiondata.shareImg,
    };
    // 用户点击右上角分享给好友,要先在分享好友这里设置menus的两个参数,才可以分享朋友圈
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  getdetail(conventionId) {
    let than = this;
    let data = {
      userId: wx.getStorageSync('userId'),
      conventionId: conventionId,
    }

    conventionDetail(data).then(function (res) {
      console.log(res)
      if (res.success) {
        let convention = res.result
        let data = {
          ...convention,
          conventionCoverPage: picUrl('activity/img/', convention.conventionCoverPage),
          conventionBlurCoverPage: picUrl('activity/img/', convention.conventionBlurCoverPage),
          detailImg: picUrl('activity/img/', convention.detailImg),
          shareImg: picUrl('activity/img/', convention.shareImg),
          avatarstatus: convention.status,
          conventionDate: convention.conventionDate.slice(5).replace("-", "/"),
          //  conventionUserMap:convention.conventionUserMap.participantlist.map((item)=>{
          //    return {...item, avatarPath:picUrl('',item.avatarPath), userPic:picUrl('',item.userPic)}
          //  }),
          sponsorUser: {
            ...convention.sponsorUser,
            avatarPath: picUrl('', convention.sponsorUser.avatarPath)
          }
        }
        wx.setStorageSync('lookCoverPage', data.conventionCoverPage); //在看的主题图片(局或者活动)，登录流程需要用到

        //判断活动是否结束
        let currentTime = formatTime(new Date()); //当前时间
        currentTime = currentTime.substring(0, currentTime.length - 3);
        let conventionEndTime = convention.conventionDate.replace(/-/g, "/") + ' ' + convention.conventionEndTime //活动结束时间
        console.log('活动结束时间')
        console.log(currentTime >= conventionEndTime)


        //传给头部headers组件的数据
        let headerdata = {
          conventionId: data.conventionId,
          // sponsorId:convention.sponsorId,
          // avatarPath:picUrl('',convention.sponsorUser.avatarPath),
          // userName:convention.sponsorUser.userName,
          islike: data.guanzhu,
          shareImg: data.shareImg
        }
        //局汇总需要的基础数据，避免重复打接口
        let conventioninfo = {
          avatarstatus: data.avatarstatus,
          conventionName: data.conventionName,
          conventionDate: data.conventionDate,
          conventionBeginTime: data.conventionBeginTime,
          conventionEndTime: data.conventionEndTime,
          conventionAddress: data.conventionAddress,
          conventionCoverPage: data.conventionCoverPage,
          conventionBlurCoverPage: data.conventionBlurCoverPage,
          conventionImageRGB: data.conventionImageRGB,
          conventionInvalidation: currentTime >= conventionEndTime, //活动是否失效
          // conventionInvalidation:false, //未结束
          headerdata
        }
        app.globalData.conventionInfo = conventioninfo

        than.setData({
          conventiondata: data,
          isloding: true,
          // headerdata,
        })

      }
    }).then(
      function () {
        than.getConventionDetail(); //大型活动数据
        than.getuserConventionOrder(); //购票
        than.getActivityList();
      }
    )

  },
})